package com.ptu.spzx.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ptu.spzx.common.exception.ptuException;
import com.ptu.spzx.domain.Delete.DeleteIds;
import com.ptu.spzx.domain.Exam.Exam;
import com.ptu.spzx.domain.Exam.Exampaper;
import com.ptu.spzx.domain.Exam.dto.*;
import com.ptu.spzx.domain.Exam.vo.*;
import com.ptu.spzx.domain.Question.po.Question;
import com.ptu.spzx.domain.Question.po.QuestionExampaper;
import com.ptu.spzx.domain.Question.po.QuestionKnowledge;
import com.ptu.spzx.domain.Stu.StuAnswer;
import com.ptu.spzx.domain.Stu.Vo.SimpleStuAnswerVo;
import com.ptu.spzx.domain.Stu.Vo.StuAnswerVo;
import com.ptu.spzx.mapper.*;
import com.ptu.spzx.model.vo.common.ResultCodeEnum;
import com.ptu.spzx.service.IExampaperService;
import com.ptu.spzx.utils.BeanCopyUtils;;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ExampaperServicerImpl extends ServiceImpl<ExampaperMapper, Exampaper> implements IExampaperService {
    @Autowired
    private ExampaperMapper exampaperMapper;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private StuAnswerMapper stuAnswerMapper;

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private QuestionKnowledgeMapper questionKnowledgeMapper;

    @Autowired
    private QuestionExampaperMapper questionExampaperMapper;


    @Override
    @Transactional
    public void addExampaper(ExamPaperDTO exampaperDTO) {
        Float epScore = 0f;
        Integer epQuestionNumber = 0;
        List<ExampaperQuestionDTO> questions = exampaperDTO.getQuestions();
        List<SimpleExampaperVVo> exampaperVVosList=new ArrayList<>();
        Long examPaperId = exampaperMapper.getMaxId();
        //批量更新
        List<Long> questionIds = new ArrayList<>();
        for (ExampaperQuestionDTO questionDto : questions) {
            String desc = questionDto.getDesc();
            String typeName = questionDto.getTypeName();
            SimpleExampaperVVo exampaperVVos=new SimpleExampaperVVo();
            List<SimpleExampaperQuestionVo> simpleExampaperQuestionDTOS = new ArrayList<>();
            SimpleExampaperQuestionVo simpleExampaperQuestionDTO=null;
            for (QuestionPaperDTO questionPaperDTO : questionDto.getQues()) {
                QuestionExampaper questionExampaper = BeanCopyUtils.copyBean(questionPaperDTO, QuestionExampaper.class);
                if(examPaperId==null){
                    long examPaper=0;
                    questionExampaper.setEpId(examPaper + 1);
                }else{
                    questionExampaper.setEpId(examPaperId + 1);
                }
                questionExampaperMapper.insert(questionExampaper);
                Long parentId = questionPaperDTO.getParentId();
                Float score = questionPaperDTO.getScore();
//                // 获取当前时间
//                LocalDateTime currentTime = LocalDateTime.now();
//                // 定义日期时间格式化器
//                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//                // 将当前时间格式化为字符串
//                String formattedDateTime = currentTime.format(formatter);
                questionIds.add(parentId);
//                questionMapper.updateUserTime(formattedDateTime,parentId);
//                questionMapper.updateByKnowIdUse(parentId);
                simpleExampaperQuestionDTO = new SimpleExampaperQuestionVo();
                simpleExampaperQuestionDTO.setQuestionId(parentId);
                simpleExampaperQuestionDTO.setOutOfOrder(questionPaperDTO.getOutOfOrder());
                simpleExampaperQuestionDTO.setQuestionType(questionPaperDTO.getQuestionType());
                simpleExampaperQuestionDTO.setDesc(desc);
                simpleExampaperQuestionDTO.setDifficultLevel(questionPaperDTO.getDifficultLevel());
//                simpleExampaperQuestionDTO.setTypeName(typeName);
                simpleExampaperQuestionDTO.setQuestionTitle(questionPaperDTO.getQuestionTitle());
                simpleExampaperQuestionDTO.setOptionsList(questionPaperDTO.getOptionsList());
                simpleExampaperQuestionDTO.setQuestionAnswer(questionPaperDTO.getQuestionAnswer());
                simpleExampaperQuestionDTO.setQuestionItem(questionPaperDTO.getQuestionItem());
                simpleExampaperQuestionDTO.setScore(score);
                simpleExampaperQuestionDTO.setIsSingleSelect(questionPaperDTO.getIsSingleSelect());
                simpleExampaperQuestionDTOS.add(simpleExampaperQuestionDTO);
//                exampaperVVos.setQuestion(simpleExampaperQuestionDTOS);
                epScore += score;
                epQuestionNumber++;
            }
            exampaperVVos.setDesc(desc);
            exampaperVVos.setQuestionType(questionDto.getQuestionType());
            exampaperVVos.setTypeName(typeName);
            exampaperVVos.setQues(simpleExampaperQuestionDTOS);
            exampaperVVosList.add(exampaperVVos);
        }
        LambdaUpdateWrapper<Question> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.in(Question::getQuestionId, questionIds); // 设置更新条件，questionId 在 questionIds 列表中
        // 设置自增更新操作
        String incrementExpression = "question_used = question_used + 1";
        lambdaUpdateWrapper.setSql(incrementExpression);
        questionMapper.update(null, lambdaUpdateWrapper);

        Exampaper exampaper = BeanCopyUtils.copyBean(exampaperDTO, Exampaper.class);
        exampaper.setQuestions(exampaperVVosList);
        exampaper.setEpScore(epScore);
        exampaper.setEpQuestionNumber(epQuestionNumber);
        exampaperMapper.insert(exampaper);
    }

    @Override
    public Exampaper selectExamPaper(Long epId) {
        if (epId == null) {
            throw new ptuException(ResultCodeEnum.PARAM_NULL);
        }
        Exampaper exampaper = exampaperMapper.selectById(epId);
        if (exampaper != null) {
            return exampaper;
        } else {
            throw new ptuException(ResultCodeEnum.DATA_NOT_EXIST);
        }
    }

    @Override
    public void deleteExamPaper(DeleteIds deleteIds) {
        List<Long> ids = deleteIds.getIds();
        if (ids == null || ids.size() == 0) {
            throw new ptuException(ResultCodeEnum.PARAM_NULL);
        }
        for (Long epId : ids) {
            questionExampaperMapper.deleteByEpId(epId);
            exampaperMapper.deleteById(epId);
        }
    }

    @Override
    public void updateExamPaper(ExamPaperDTO examPaperDTO) {
        Long epId = examPaperDTO.getEpId();
        Exampaper exampaperExist = exampaperMapper.selectById(epId);
        if (exampaperExist == null) {
            throw new ptuException(ResultCodeEnum.DATA_NOT_EXIST);
        }
        Float epScore = 0f;
        Integer epQuestionNumber = 0;
        List<ExampaperQuestionDTO> questions = examPaperDTO.getQuestions();
        List<SimpleExampaperVVo> exampaperVVosList=new ArrayList<>();
        for (ExampaperQuestionDTO questionDto : questions) {
            List<SimpleExampaperQuestionVo> simpleExampaperQuestionDTOS = new ArrayList<>();
            SimpleExampaperVVo exampaperVVos=new SimpleExampaperVVo();
            String desc = questionDto.getDesc();
            String typeName = questionDto.getTypeName();
            for (QuestionPaperDTO questionPaperDTO : questionDto.getQues()) {
                QuestionExampaper questionExampaper = BeanCopyUtils.copyBean(questionPaperDTO, QuestionExampaper.class);
                Long parentId = questionPaperDTO.getParentId();
                UpdateWrapper<QuestionExampaper> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("parent_id", parentId) // 匹配parentId字段
                        .eq("ep_id", epId);
                // 执行更新操作
                questionExampaperMapper.update(questionExampaper, updateWrapper);
                Float score = questionPaperDTO.getScore();
                SimpleExampaperQuestionVo simpleExampaperQuestionDTO = new SimpleExampaperQuestionVo();
                simpleExampaperQuestionDTO.setQuestionId(parentId);
                simpleExampaperQuestionDTO.setOutOfOrder(questionPaperDTO.getOutOfOrder());
                simpleExampaperQuestionDTO.setQuestionType(questionPaperDTO.getQuestionType());
                simpleExampaperQuestionDTO.setDesc(desc);
//                simpleExampaperQuestionDTO.setTypeName(typeName);
                simpleExampaperQuestionDTO.setQuestionTitle(questionPaperDTO.getQuestionTitle());
                simpleExampaperQuestionDTO.setOptionsList(questionPaperDTO.getOptionsList());
                simpleExampaperQuestionDTO.setQuestionAnswer(questionPaperDTO.getQuestionAnswer());
                simpleExampaperQuestionDTO.setQuestionItem(questionPaperDTO.getQuestionItem());
                simpleExampaperQuestionDTO.setScore(score);
                simpleExampaperQuestionDTO.setDifficultLevel(questionPaperDTO.getDifficultLevel());
                simpleExampaperQuestionDTO.setIsSingleSelect(questionPaperDTO.getIsSingleSelect());
                simpleExampaperQuestionDTOS.add(simpleExampaperQuestionDTO);
                epScore += score;
                epQuestionNumber++;
            }
            exampaperVVos.setDesc(desc);
            exampaperVVos.setQuestionType(questionDto.getQuestionType());
            exampaperVVos.setTypeName(typeName);
            exampaperVVos.setQues(simpleExampaperQuestionDTOS);
            exampaperVVosList.add(exampaperVVos);
        }
        Exampaper exampaper = BeanCopyUtils.copyBean(examPaperDTO, Exampaper.class);
        exampaper.setQuestions(exampaperVVosList);
        exampaper.setEpScore(epScore);
        exampaper.setEpQuestionNumber(epQuestionNumber);
        exampaperMapper.updateById(exampaper);
    }


    @Override
    public PageInfo<Exampaper> getExamPaperByCreator(Integer courseId, String creator, Integer pageNum, Integer pageSize) {
        LambdaQueryWrapper<Exampaper> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(courseId != null, Exampaper::getBelongCourseId, courseId)
                .eq(StringUtils.isNotBlank(creator), Exampaper::getCreator, creator);
        PageHelper.startPage(pageNum, pageSize);
        List<Exampaper> exampapers = exampaperMapper.selectList(lambdaQueryWrapper);
        PageInfo<Exampaper> pageInfo = new PageInfo<>(exampapers);
        return pageInfo;
    }

    @Override
    public ExamPaperVo getExampaperWithAnswer(Long examId, String stuId) {
        LambdaQueryWrapper<StuAnswer> lqw = new LambdaQueryWrapper<>();
        lqw.eq(StuAnswer::getStuId, stuId).eq(StuAnswer::getExamId, examId);
        StuAnswer stuAnswer = stuAnswerMapper.selectOne(lqw);
        if (stuAnswer != null) {
            throw new ptuException(ResultCodeEnum.DATA_EXIST);
        }
        //考试的相关判断
        Exam exam = examMapper.selectById(examId);
        if (exam == null) {
            throw new ptuException(ResultCodeEnum.DATA_NOT_EXIST);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date publishTime = null;
        Date startTime = null;
        Date endTime = null;
        try {
            publishTime = sdf.parse(exam.getExamPublishTime());
            startTime = sdf.parse(exam.getExamBeginTime());
            endTime = sdf.parse(exam.getExamEndTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long current = Calendar.getInstance().getTimeInMillis();
        long publish = current - publishTime.getTime();
        long start = current - startTime.getTime();
        long end = current - endTime.getTime();
        if (publish < 0) {
            throw new ptuException(ResultCodeEnum.TIME_NOT_BEGIN);
        } else if (publish >= 0 && start < 0) {
            throw new ptuException(ResultCodeEnum.TIME_NOT_BEGIN);
        } else if (start >= 0 && end < 0) {
            //获取随机试卷
            List<Long> examPaperIds = exampaperMapper.SelectByIds(examId);
//            for (Long epId:examPaperIds){
//                List<Long> questionIds=questionExampaperMapper.selectByEpId(epId);
////           更新题目时间
//            // 获取当前时间
//            LocalDateTime currentTime = LocalDateTime.now();
//            // 定义日期时间格式化器
//            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//            // 将当前时间格式化为字符串
//            String formattedDateTime = currentTime.format(formatter);
//            UpdateWrapper<Question> updateWrapper = new UpdateWrapper<>();
//            updateWrapper.in("question_id", questionIds);
//            updateWrapper.set("used_time", formattedDateTime);
//            questionMapper.update(null, updateWrapper);
//            }
            //分割线
            Random random = new Random();
            int randomEpId = random.nextInt(examPaperIds.size());
            Long epId = examPaperIds.get(randomEpId);
            Exampaper exampaper = exampaperMapper.selectById(epId);
//            List<SimpleExampaperQuestionVo> epAnswers = exampaper.getEpAnswer();
            List<SimpleExampaperVVo> epAnswer1 = exampaper.getQuestions();
            List<ExamPaperVVo> examPaperVVos=new ArrayList<>();;
            for(Object simpleExamPaperVo:epAnswer1){
                ExamPaperVVo examPaperVVo=new ExamPaperVVo();
                String jsonString = JSON.toJSONString(simpleExamPaperVo);
                SimpleExampaperVVo simpleExampaperQuestion = JSONObject.parseObject(jsonString,SimpleExampaperVVo.class);
                String typeName = simpleExampaperQuestion.getTypeName();
                List<SimpleExampaperQuestionVo> epAnswers = simpleExampaperQuestion.getQues();
                List<SimpleExamPaperVo> simpleExamPaperVos = new ArrayList<SimpleExamPaperVo>();
                for (Object epAnswer : epAnswers) {
                    String jsonObject = JSON.toJSONString(epAnswer);
                    SimpleExamPaperVo simpleExampaperQuestionVo = JSONObject.parseObject(jsonObject, SimpleExamPaperVo.class);
                    simpleExamPaperVos.add(simpleExampaperQuestionVo);
                }
                examPaperVVo.setTypeName(typeName);
                examPaperVVo.setEpNoAnswer(simpleExamPaperVos);
                examPaperVVos.add(examPaperVVo);
            }
//            List<SimpleExamPaperVo> simpleExamPaperVos = new ArrayList<SimpleExamPaperVo>();
//            for (Object epAnswer : epAnswers) {
//                String jsonObject = JSON.toJSONString(epAnswer);
//                SimpleExamPaperVo simpleExampaperQuestionVo = JSONObject.parseObject(jsonObject, SimpleExamPaperVo.class);
//                simpleExamPaperVos.add(simpleExampaperQuestionVo);
//            }
            ExamPaperVo examPaperVo = BeanCopyUtils.copyBean(exampaper, ExamPaperVo.class);
            examPaperVo.setEpAnswer(examPaperVVos);
            return examPaperVo;
        } else {
            throw new ptuException(ResultCodeEnum.TIME_BEGIN);
        }
    }

    @Override
    public StuAnswerVo getStuAnswer(Long examId) {
        Exam exam = examMapper.selectById(examId);
        if (exam == null) {
            throw new ptuException(ResultCodeEnum.DATA_NOT_EXIST);
        }
        LambdaQueryWrapper<StuAnswer> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StuAnswer::getExamId, examId);
        List<StuAnswer> stuAnswers = stuAnswerMapper.selectList(lambdaQueryWrapper);
        List<String> stuIds = new ArrayList<>();
        for (StuAnswer stuAnswer : stuAnswers) {
            //1代表试卷可改
            if (stuAnswer.getEpStatus() == 1) {
                String stuId = stuAnswer.getStuId();
                System.out.println(stuId);
                stuIds.add(stuId);
            }
        }
        if (stuIds.isEmpty()) {
            throw new ptuException(ResultCodeEnum.DATA_NOT_EXIST);
        }
        //时间的转化
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String examBeginTime = exam.getExamBeginTime();
        Date beginTime = null;
        long current = Calendar.getInstance().getTimeInMillis();
        try {
            beginTime = sdf.parse(examBeginTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (current - beginTime.getTime() >= 0) {
            int Random = new Random().nextInt(stuIds.size());
            String randomNStuId = stuIds.get(Random);
            StuAnswer stuAnswer = stuAnswerMapper.SelectByStuIdAndExamId(randomNStuId, examId);
            String answer = stuAnswer.getStuAnswer();
            JsonNode stuAnwser;
            ObjectMapper objectMapper = new ObjectMapper()
                    .enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT)
                    .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
            try {
                stuAnwser = objectMapper.readValue(answer, JsonNode.class);
            } catch (Exception e) {
                throw new ptuException(ResultCodeEnum.DATA_ERROR);
            }
            //获取试卷
            Long epId = stuAnswer.getEpId();
            Exampaper exampaper = exampaperMapper.selectById(epId);
//            List<SimpleExampaperQuestionVo> epAnswers = exampaper.getEpAnswer();
            List<SimpleExampaperVVo> epAnswer1 = exampaper.getQuestions();
            List<SimpleStuAnswerVo> simpleStuAnswerVos = new ArrayList<>();
            for(Object epAnswe:epAnswer1){
                String jsonObjectA = JSON.toJSONString(epAnswe);
                SimpleExampaperVVo simpleExampaperQuestion = JSONObject.parseObject(jsonObjectA,SimpleExampaperVVo.class);
                List<SimpleExampaperQuestionVo> epAnswers= simpleExampaperQuestion.getQues();
                int a = 0;
                for (Object epAnswer : epAnswers) {
                    String jsonObject = JSON.toJSONString(epAnswer);
                    SimpleStuAnswerVo simpleStuAnswerVo = JSONObject.parseObject(jsonObject, SimpleStuAnswerVo.class);
                    simpleStuAnswerVo.setStuAnswer(stuAnwser.get(a).get("questionAnswer").asText());
                    simpleStuAnswerVos.add(simpleStuAnswerVo);
                    a += 1;
                }
            }
            StuAnswerVo stuAnswerVo = BeanCopyUtils.copyBean(stuAnswer, StuAnswerVo.class);
            stuAnswerVo.setStuAnswer(simpleStuAnswerVos);
            Integer result = stuAnswerMapper.updateEpStatus(stuAnswer.getStuId());
            if (stuAnswerVo != null && result == 1) {
                return stuAnswerVo;
            } else {
                throw new ptuException(ResultCodeEnum.DATA_NOT_EXIST);
            }
        } else {
            throw new ptuException(ResultCodeEnum.TIME_NOT_BEGIN);
        }
    }

    @Override
    public PageInfo<Exampaper> getExamPaperByExamId(List<Long> examIds, Integer pageNum, Integer pageSize) {
        if (examIds == null) {
            throw new ptuException(ResultCodeEnum.PARAM_NULL);
        }
        List<Long> epIds = new ArrayList<>();
        for (Long examId : examIds) {
            List<Long> epId = exampaperMapper.SelectByIds(examId);
            if (epId == null) {
                throw new ptuException(ResultCodeEnum.DATA_NOT_EXIST);
            }
            epIds.addAll(epId);
        }
        if (epIds == null) {
            throw new ptuException(ResultCodeEnum.DATA_NOT_EXIST);
        }
        LambdaQueryWrapper<Exampaper> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(Exampaper::getEpId, epIds);
        PageHelper.startPage(pageNum, pageSize);
        List<Exampaper> exampapers = exampaperMapper.selectList(lambdaQueryWrapper);
        PageInfo<Exampaper> pageInfo = new PageInfo<>(exampapers);
        return pageInfo;
    }

    @Override
    public PageInfo<Exampaper> getExamPaperByCourseId(List<Long> courseIds, Integer pageNum, Integer pageSize) {
        LambdaQueryWrapper<Exampaper> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Exampaper::getBelongCourseId, courseIds);
        PageHelper.startPage(pageNum, pageSize);
        List<Exampaper> exampapers = exampaperMapper.selectList(queryWrapper);
        PageInfo<Exampaper> pageInfo = new PageInfo<>(exampapers);
        return pageInfo;
    }

    private String getKnowledgeQuestion(Long knowledgeId) {
        return "knowledge:question" + knowledgeId;
    }

    @Override
    public void autoAddExamPaper(AutoAddExamPaper autoAddExamPaper) {
        //获取全部题目
        List<Question> questionInfoLists = new ArrayList<>();
        //获取交集题目
        List<Question> commonQuestion = new ArrayList<>();
        Map<Question, Integer> map = new HashMap<>();
        //插入类
        List<SimpleExampaperQuestionVo> simpleExampaperQuestionDTOS = new ArrayList<>();
        List<SimpleExampaperVVo> exampaperVVosList=new ArrayList<>();
        SimpleExampaperVVo simpleExampaperVVo=new SimpleExampaperVVo();
        //分数
        Float epScore = 0f;
        Integer epQuestionNumber = 0;
        List<Long> knowledgeId = null;
        List<AutoExamPaperQuestionDto> questions = autoAddExamPaper.getQuestions();
        List<Long> usedQuestion = new ArrayList<>();
        for (AutoExamPaperQuestionDto showQuestion : questions) {
            String desc = showQuestion.getDesc();
            String typeName = showQuestion.getTypeName();
            Float score = showQuestion.getScore();
            knowledgeId = showQuestion.getKnowledgeId();
            Integer questionType = showQuestion.getQuestionType();
            Integer isSingleSelect = showQuestion.getIsSingleSelect();
            //更新redis里面的数据
            getQuestionRedis(knowledgeId);
            //取出redis里面的数据
            for (Long knowledge : knowledgeId) {
                String knowledgeQuestionKey = this.getKnowledgeQuestion(knowledge);
                List<Object> valueList = redisTemplate.opsForHash().values(knowledgeQuestionKey);
                //List<Object>-->List<Question>
                if (!CollectionUtils.isEmpty(valueList)) {
                    List<Question> questionInfoList = valueList.stream().map(questionInfo ->
                                    JSON.parseObject(questionInfo.toString(), Question.class))
                            .collect(Collectors.toList());
                    questionInfoLists.addAll(questionInfoList);
                }
            }
            System.out.println(questionInfoLists);
            //获取关于知识点的不重复总题目
            HashSet<Question> set = new HashSet<>(questionInfoLists);
            List<Question> singleQuestion = new ArrayList<>(set);
            //获取共同知识点的总题目
            for (Question question : questionInfoLists) {
                map.put(question, map.getOrDefault(question, 0) + 1);
                if (map.get(question) != null && !commonQuestion.contains(question)) {
                    commonQuestion.add(question);
                }
            }
            //根据type,isSingle来获取相关题目
            List<Question> commonQuestionType = new ArrayList<>();
            //针对多选题的刷选
            List<Question> manyChoice = new ArrayList<>();
            if (commonQuestion != null) {
                System.out.println(commonQuestion);
                for (Question question : commonQuestion) {
                    Integer questionType1 = question.getQuestionType();
                    Integer isSingleSelect1 = question.getIsSingleSelect();
                    if (questionType1 == questionType) {
                        //针对多选题的选择
                        if (questionType1 == 0 && isSingleSelect1 == isSingleSelect) {
                            manyChoice.add(question);
                        } else {
                            commonQuestionType.add(question);
                        }
                    }
                }
            } else {
                for (Question question : singleQuestion) {
                    Integer questionType1 = question.getQuestionType();
                    Integer isSingleSelect1 = question.getIsSingleSelect();
                    if (questionType1 == questionType) {
                        //针对多选题的选择
                        if (questionType1 == 0 && isSingleSelect1 == isSingleSelect) {
                            manyChoice.add(question);
                        } else {
                            commonQuestionType.add(question);
                        }
                    }
                }
            }
            Random random = new Random();
            int number;
            Question question = null;
            if (manyChoice.size() != 0) {
                number = random.nextInt(manyChoice.size());
                question = manyChoice.get(number);
                Long questionId = question.getQuestionId();
                if (usedQuestion.contains(questionId)) {
                    throw new ptuException(ResultCodeEnum.DATA_EXIST);
                }
                questionMapper.updateByKnowIdUse(questionId);
                //更新redis里面的数据
                Question question1 = questionMapper.selectById(questionId);
                List<Long> knowlegeIds = questionKnowledgeMapper.selectByQuestion(questionId);
                for (Long knowledge : knowlegeIds) {
                    String knowledgeQuestionKey = this.getKnowledgeQuestion(knowledge);
                    redisTemplate.opsForHash().delete(knowledgeQuestionKey, questionId);
                    redisTemplate.opsForHash().put(knowledgeQuestionKey,
                            String.valueOf(questionId),
                            JSON.toJSONString(question1));
                }
                usedQuestion.add(questionId);
            } else if (commonQuestionType.size() != 0) {
                number = random.nextInt(commonQuestionType.size());
                question = commonQuestionType.get(number);
                Long questionId = question.getQuestionId();
                if (usedQuestion.contains(questionId)) {
                    throw new ptuException(ResultCodeEnum.DATA_EXIST);
                }
                questionMapper.updateByKnowIdUse(questionId);
                //更新redis里面的数据
                Question question1 = questionMapper.selectById(questionId);
                List<Long> knowlegeIds = questionKnowledgeMapper.selectByQuestion(questionId);
                for (Long knowledge : knowlegeIds) {
                    String knowledgeQuestionKey = this.getKnowledgeQuestion(knowledge);
                    redisTemplate.opsForHash().delete(knowledgeQuestionKey, questionId);
                    redisTemplate.opsForHash().put(knowledgeQuestionKey,
                            String.valueOf(questionId),
                            JSON.toJSONString(question1));
                }
                usedQuestion.add(questionId);
            }
            SimpleExampaperQuestionVo simpleExampaperQuestionDTO = new SimpleExampaperQuestionVo();
            simpleExampaperQuestionDTO.setQuestionId(question.getQuestionId());
            simpleExampaperQuestionDTO.setOutOfOrder(question.getOutOfOrder());
            simpleExampaperQuestionDTO.setQuestionType(question.getQuestionType());
            simpleExampaperQuestionDTO.setDesc(desc);
            simpleExampaperQuestionDTO.setQuestionTitle(question.getQuestionTitle());
            simpleExampaperQuestionDTO.setOptionsList(question.getOptionsList());
            simpleExampaperQuestionDTO.setQuestionAnswer(question.getQuestionAnswer());
            simpleExampaperQuestionDTO.setQuestionItem(question.getQuestionItem());
            simpleExampaperQuestionDTO.setScore(score);
            simpleExampaperQuestionDTO.setIsSingleSelect(question.getIsSingleSelect());
            simpleExampaperQuestionDTOS.add(simpleExampaperQuestionDTO);
            simpleExampaperVVo.setTypeName(typeName);
            simpleExampaperVVo.setQues(simpleExampaperQuestionDTOS);
            exampaperVVosList.add(simpleExampaperVVo);
            epScore += score;
            epQuestionNumber++;
        }
        Exampaper exampaper = BeanCopyUtils.copyBean(autoAddExamPaper, Exampaper.class);
        exampaper.setQuestions(exampaperVVosList);
        exampaper.setEpScore(epScore);
        exampaper.setEpQuestionNumber(epQuestionNumber);
        exampaperMapper.insert(exampaper);

    }

    public void getQuestionRedis(List<Long> knowledgeIds) {
        for (Long knowledge : knowledgeIds) {
            List<Long> questionIds = questionKnowledgeMapper.selectByKnowledge(knowledge);
            LambdaQueryWrapper<Question> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.in(Question::getQuestionId, questionIds);
            lambdaQueryWrapper.orderByAsc(Question::getQuestionUsed);
            List<Question> questions = questionMapper.selectList(lambdaQueryWrapper);
            int used = questions.get(0).getQuestionUsed();
            List<Long> leastUsedQuestionIds = questions.stream()
                    .filter(question -> question.getQuestionUsed() == used) // 过滤出使用次数最少的题目
                    .map(Question::getQuestionId)
                    .collect(Collectors.toList());
            //构建hash里面键的名称
            String knowledgeQuestionKey = this.getKnowledgeQuestion(knowledge);
            for (Long questionId : leastUsedQuestionIds) {
                //hash类型,key:knowledgeId field:questionId,value:question信息
                Object questionInfoObj =
                        redisTemplate.opsForHash().get(knowledgeQuestionKey, String.valueOf(questionId));
                //创建一个空对象
                Question question = null;
                if (questionInfoObj != null) {
                    question = JSON.parseObject(questionInfoObj.toString(), Question.class);
                } else {
                    //判断是否存在，如果不存在，则添加到redis
                    //添加题目到redis里面
                    question = questionMapper.selectById(questionId);
                }
                //添加到redis里面去
                redisTemplate.opsForHash().put(knowledgeQuestionKey,
                        String.valueOf(questionId),
                        JSON.toJSONString(question));
            }
        }
    }
}
